#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: Florian Dorn <florian.dorn@gmail.com>
# @package: agenda
# @license: GNU GPLv2
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

import gtk
import gtk.glade
from gettext import gettext as _

import gobject
from agenda.ui.AccelEntry import AccelEntry
from agenda.static import APP_VERSION, APP_NAME
from agenda import GLADEFILE
from agenda import Keybinder
from agenda.pluginsystem import *
import agenda

tt = gtk.Window()
tt.set_name('gtk-tooltip')
tt.ensure_style()
tt_style = tt.get_style().copy()
tt.hide()
tt.unrealize()


class PrefDialog:
	def __init__(self,database,agenda):
		self._database = database
		
		self._agenda = agenda
		self.wTree = gtk.glade.XML(GLADEFILE)
		self.dlg = self.wTree.get_widget("preferencedialog")
		self.dlg.set_modal(False)
		
		#pref_info = self.wTree.get_widget("pref_info")
		#pref_info.modify_bg(pref_info.state,pref_info.style.white)
		
		btn = self.wTree.get_widget("pref_button_close")
		btn.connect("activate",self.on_close)
		btn.connect("clicked",self.on_close)
		self.dlg.connect("delete-event",self.on_close)
		
		self.notebook = self.wTree.get_widget("pref_notebook")
		self.notebook.connect("switch-page",self.on_notebook_set_page_cb)
		
		pref_make_white = self.wTree.get_widget("pref_make_white")
		pref_make_white.modify_bg(pref_make_white.state,pref_make_white.style.white)
		
		self.tbuttons = []
		
		
		self.tbuttons.append(self.wTree.get_widget("togglebutton_general"))
		self.tbuttons.append(self.wTree.get_widget("togglebutton_cals"))
		self.tbuttons.append(self.wTree.get_widget("togglebutton_plugins"))
		for num,btn in enumerate(self.tbuttons):
			btn.connect("button-press-event",self.custon_btn_press_event)
			btn.set_data('page',num)
			btn.set_style(tt_style)

		self.notebook.set_current_page(0)
		self.on_notebook_set_page_cb(self.notebook,None,0)
		#self.notebook.set_show_tabs(False)

		self._style_source = self.dlg.connect ("notify::style", self.theme_changed_cb) # gtk theme changes

		self.dlg.ensure_style()	#make sure we have a style (minimized windows don't so the theme won't be changed
		pass

	def theme_changed_cb(self, obj=None, prop=None):
		
		self.__base_icon_pixbuf = agenda.load_stock_image(gtk.STOCK_PREFERENCES,gtk.ICON_SIZE_SMALL_TOOLBAR)
		self.set_icon_pixbuf(self.__base_icon_pixbuf)

	def set_icon_pixbuf(self,pixbuf):
		self.dlg.set_icon(pixbuf)
		#self.window.set_icon( pixbuf )
		#self.window.queue_draw()

	def custon_btn_press_event(self,btn,event):
		if event.button == 1:
			self.notebook.set_current_page(btn.get_data('page'))
		
	#def custom_btn_clicked_cb(self,btn,data=None):
	#	if btn.get_active():
			
	def on_notebook_set_page_cb(self,notebook,page,page_num=None):
		
		for tb in self.tbuttons:
			tb.set_visible_window(tb.get_data('page') == page_num)
			#tb.set_sensitive(tb.get_data('page') != page_num)
	def on_activate_provider(self,widget = None, provider = None,cals = []): 
		try:
			page = self.wTree.get_widget("%s_page" %provider)
			if(widget.get_active()):
				page.show()
			else:
				page.hide()
		except Exception,e:
			pass
		self._database.toggle_provider_active(provider,widget.get_active())				

		pass
	def on_calendar_toggled_cb(self,cell, path, user_data):
		"""Callback for activating/deavtivating a calendar""" 
		model, column = user_data
		model[path][column] = not model[path][column]
		calendar_id = model[path][0]
		self._database.setCalendarHidden(calendar_id,model[path][column])
		return
		
	def mk_calendar_treeview(self,calendars):
		calendars.sort()
		#liststore: ID, visible, name
		liststore = gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_BOOLEAN,gobject.TYPE_STRING)
		treeview = gtk.TreeView(liststore)
		treeview.set_headers_visible(False)
		treeview.set_rules_hint(True)
		
		bool_cell = gtk.CellRendererToggle()
		bool_cell.set_property("activatable", True)

		bcolumn = gtk.TreeViewColumn('')
		bcolumn.pack_start(bool_cell)
		bcolumn.add_attribute(bool_cell,'active',1)
		bool_cell.connect("toggled", self.on_calendar_toggled_cb, (liststore, 1))

		name_col = gtk.TreeViewColumn('')
		
		treeview.append_column(bcolumn)
		treeview.append_column(name_col)
		name_cell = gtk.CellRendererText()

		name_col.pack_start(name_cell)
		name_col.add_attribute(name_cell,'markup',2)

		for row in calendars:
			#TODO: get the visible flag from the calendar
			liststore.append([row.id,row.get_visible(),gobject.markup_escape_text( row.get_name() )])
		return treeview

	def on_keyboard_shortcut_entry_changed(self, entry, accel_name, keyval, mods, keycode):        
		if accel_name != "":
			self._agenda.set_keybinding(accel_name)
			self._agenda.bind_keybinding(accel_name)
		return False
	def get_config(self,path):
		"""
		get a value from the configuration file
		"""
		return self._database.get_option(path)

	def set_config(self,path,value):
		self._database.set_option(path,value)
		
	def provider_properties_cb(self,btn=None,provider=None):
		print "TODO: opening properites for:" % provider
	def run(self):
		#dynamically build the list of active sources
		
		providers = get_by_capability('provider')
		active_providers = []
		active_providers = self.get_config('active_providers')
		
		#Populate the active calendar tree
		active_calendar_box = self.wTree.get_widget("active_calendar_box")

		active_calendar_sources = []
		for provider in providers:
			
			l = gtk.Label()
			l.set_markup('<b>%s</b>' % provider.Plugin_Name)
			l.set_alignment(0,0.5)
			
			hbox = gtk.HBox()
			
			checkbox = gtk.CheckButton()
			checkbox.add(l)
			
				
			checkbox.set_active( provider.__module__ in active_providers )	
			checkbox.connect("toggled",self.on_activate_provider,provider)
			#checkbox.set_active( provider.__module__ in active_providers )	
			checkbox.emit("toggled")

			hbox.pack_start(checkbox)
			
			if provider.has_config_widget():
				cfg_btn = gtk.Button()
				cfg_btn.add(gtk.image_new_from_stock("gtk-properties",gtk.ICON_SIZE_MENU))
				cfg_btn.set_relief(gtk.RELIEF_NONE)
				cfg_btn.connect("clicked",self.provider_properties_cb,provider)
				hbox.pack_start(cfg_btn,False,False)
						
			active_calendar_box.pack_start(hbox,False,False)

			
			calendars = self._database.getCalendars(provider)
			if len(calendars) > 0:
				treeview = self.mk_calendar_treeview(calendars)
				treeview.show()
				alignment = gtk.Alignment(0,0,1,0)
				alignment.set_padding(0,0,20,0)
				alignment.add(treeview)
				active_calendar_box.pack_start(alignment,False,False)
			

			
			active_calendar_sources.append(checkbox)
			
		active_calendar_box.show_all()
		
		keybinding_entry_container = self.wTree.get_widget("keybinding_entry_container")
		l = self.wTree.get_widget("no_keybinder_info")
		if(Keybinder):
			keyboard_shortcut_entry = AccelEntry()
			keyboard_shortcut_entry.connect('accel-edited', self.on_keyboard_shortcut_entry_changed)
			keyboard_shortcut_entry.get_widget().show()
			keybinding_entry_container.pack_start(keyboard_shortcut_entry.get_widget(), True)
			keyboard_shortcut_entry.set_accelerator_name(self.get_config('accelerator'))
			l.hide()


		
		#google-calendar
		try:
			
			pref_gcal_username = self.wTree.get_widget("pref_gcal_username")
			pref_gcal_password = self.wTree.get_widget("pref_gcal_password")
			pref_gcal_username.set_text(self.get_config('plugins/GoogleCalendar/username'))
			password = self.get_config('plugins/GoogleCalendar/password')
			pref_gcal_password.set_text("%s" % password)
		except Exception,e:
			print e
			pass
		#groupwise
		try:
			pref_gw_server			 = self.wTree.get_widget("pref_gw_server")
			pref_gw_username		   = self.wTree.get_widget("pref_gw_username")
			pref_gw_password		   = self.wTree.get_widget("pref_gw_password")
			pref_gw_connection_ssl  = self.wTree.get_widget("pref_gw_connection_ssl")
			pref_gw_connection_normal	   = self.wTree.get_widget("pref_gw_connection_normal")
			pref_gw_port_normal	 = self.wTree.get_widget("pref_gw_port_normal")
			pref_gw_port_ssl		   = self.wTree.get_widget("pref_gw_port_ssl")
			pref_gw_folder			 = self.wTree.get_widget("pref_gw_folder")
			pref_gw_tzadjust		   = self.wTree.get_widget("pref_gw_tzadjust")



			pref_gw_server.set_text(self.get_config('plugins/Groupwise/server'))
			pref_gw_username.set_text(self.get_config('plugins/Groupwise/username'))
			pref_gw_password.set_text(self.get_config('plugins/Groupwise/password'))
			if(bool(self.get_config('plugins/Groupwise/ssl'))):
				pref_gw_connection_ssl.set_active(True)
			else:
				pref_gw_connection_normal.set_active(True)
			pref_gw_port_normal.set_value(float(self.get_config('plugins/Groupwise/port_normal')))
			pref_gw_port_ssl.set_value(float(self.get_config('plugins/Groupwise/port_ssl')))
			pref_gw_folder.set_text(self.get_config('plugins/Groupwise/folder'))
			pref_gw_tzadjust.set_value(float(self.get_config('plugins/Groupwise/timezoneadjust')))
		except:
			pass

		pref_refresh = self.wTree.get_widget("pref_refresh")
		pref_reminder = self.wTree.get_widget("pref_reminder")	
		pref_days = self.wTree.get_widget("pref_days")		

		pref_refresh.set_value(float(self.get_config('refresh')))
		pref_reminder.set_value(float(self.get_config('reminder')))
		pref_days.set_value(float(self.get_config('num_days')))
		#get_active()
		#process the settings
		self.dlg.set_default_size(600,650)
		return self.dlg.run()
	def write(self):
		"""
		write the configuration
		"""
		self._database.config.sync()
	def present(self):
		self.dlg.present()
	def on_close(self,widget,event= None):
		#print widget
		#print event
		#google-calendar
		try:
			pref_gcal_username = self.wTree.get_widget("pref_gcal_username")
			pref_gcal_password = self.wTree.get_widget("pref_gcal_password")
			self.set_config('plugins/GoogleCalendar/username',pref_gcal_username.get_text())
			self.set_config('plugins/GoogleCalendar/password',pref_gcal_password.get_text())

		except Exception,e:
			print e
			pass
		#groupwise
		try:
			pref_gw_server			 = self.wTree.get_widget("pref_gw_server")
			pref_gw_username		   = self.wTree.get_widget("pref_gw_username")
			pref_gw_password		   = self.wTree.get_widget("pref_gw_password")
			pref_gw_connection_ssl  = self.wTree.get_widget("pref_gw_connection_ssl")
			pref_gw_connection_normal	   = self.wTree.get_widget("pref_gw_connection_normal")
			pref_gw_port_normal	 = self.wTree.get_widget("pref_gw_port_normal")
			pref_gw_port_ssl		   = self.wTree.get_widget("pref_gw_port_ssl")
			pref_gw_folder			 = self.wTree.get_widget("pref_gw_folder")
			pref_gw_tzadjust		   = self.wTree.get_widget("pref_gw_tzadjust")

			self.set_config('plugins/Groupwise/server', pref_gw_server.get_text())
			self.set_config('plugins/Groupwise/username', pref_gw_username.get_text())
			self.set_config('plugins/Groupwise/password', pref_gw_password.get_text())
			self.set_config('plugins/Groupwise/ssl', pref_gw_connection_ssl.get_active())
			self.set_config('plugins/Groupwise/port_normal', pref_gw_port_normal.get_text())
			self.set_config('plugins/Groupwise/port_ssl',pref_gw_port_ssl.get_text())
			self.set_config('plugins/Groupwise/folder',pref_gw_folder.get_text())			 
			self.set_config('plugins/Groupwise/timezoneadjust',pref_gw_tzadjust.get_text())					   
		except:
			pass

		pref_refresh = self.wTree.get_widget("pref_refresh")
		pref_reminder = self.wTree.get_widget("pref_reminder")	
		pref_days = self.wTree.get_widget("pref_days")

		self.set_config('refresh',pref_refresh.get_text())
		self.set_config('reminder',pref_reminder.get_text())
		self.set_config('num_days',pref_days.get_text())
		
		self.write()
		self.dlg.destroy()		
